#pragma once

#include <functional>
#include <string>
#include <iostream>
#include <unistd.h>
#include "log.hpp"

class Task
{
    using func_t = std::function<void(int)>;

public:
    Task()
    {
    }
    Task(int sock, func_t func)
        : _sock(sock), _callback(func)
    {
    }

    void operator()()
    {
        return _callback(_sock);
    }

private:
    int _sock;
    func_t _callback;
};

void ServiceIo(int sock)
{
    char buffer[1024];
    while (true)
    {
        int n = read(sock, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            // 暂时把读到的当成字符串
            buffer[n] = 0;

            std::cout << "recv message:" << buffer << std::endl;
            std::string message = buffer;
            message += "Server[echo]";

            write(sock, message.c_str(), message.size());
        }
        else if (n == 0) // 代表client退出通信
        {
            logMessage(NORMAL, "Client exit");
            break;
        }
    }
    close(sock);
}